// 1. 导入 express与mysql模块
const express = require("express");

const cors = require("cors");

const mysql = require("mysql");

// 与mysql建立连接

const db = mysql.createPool({
  host: "127.0.0.1",
  user: "root",
  password: "root",
  database: "my_db_01"
});

const app = express();
app.use(cors());
// 创建一个中间件用于将post提交过来的数据解析为对象
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// 创建路由
app.post("/addUser", (req, res) => {
  const body = req.body;
  //   console.log(body);

  //   const sqlStr = "insert into users set username = ? , password = ?";
  const sqlStr = "insert into users set ? ";

  db.query(sqlStr, body, (err, data) => {
    if (err) return console.log(err.message);

    if (data.affectedRows === 1) {
      res.send({
        status: 0,
        msg: "数据添加成功"
      });
    }
  });
});

// 定义一个接口用于获取数据
app.get("/getUser", (req, res) => {
  const sqlStr = "select * from users";
  db.query(sqlStr, (err, data) => {
    if (err) return console.log(err.message);
    res.send({
      status: 0,
      msg: "数据查询成功",
      data
    });
  });
});

app.get("/editUser/:id", (req, res) => {
  const id = req.params.id;
  //   return console.log(id);

  const user = { username: "小张", password: "1111", id };

  // 构建 sql语句
  const sqlStr = "update users set ? where id = ?";

  db.query(sqlStr, [user, id], (err, data) => {
    if (err) return console.log(err.message);
    if (data.affectedRows === 1) {
      res.send({
        status: 0,
        msg: "数据更新成功"
      });
    }
  });
});

app.delete("/delUser/:id", (req, res) => {
  const id = req.params.id;
  // const sqlStr = "delete from users where id = " + id;
  const sqlStr = "delete from users where id = ?";

  db.query(sqlStr, [id], (err, data) => {
    if (err) return console.log(err.message);

    if (data.affectedRows === 1) {
      res.send({
        status: 0,
        msg: "数据已经被删除"
      });
    }
  });
});

app.listen(80, () => {
  console.log("http://127.0.0.1");
});
